<template>
  <el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>更换头像</span>
  </div>
  <div class="two">
    <img src="@/assets/images/avatar.jpg" alt="" v-if="url === ''">
    <img :src="url" alt="" v-else>
  </div>
  <div class="one">
    <el-button type="primary" icon="el-icon-plus" @click="$refs.preview.click()">选择图片</el-button>
    <el-button type="success" :disabled="url === ''" icon="el-icon-upload" @click="uploading">上传头像</el-button>
    <input type="file" style="display:none" ref="preview" @change="file">
  </div>
</el-card>
</template>

<script>
import { updateAvatarAPI } from '@/api/user'
export default {
  data() {
    return {
      url: '',
      disabled: 'false'
    }
  },
  methods: {
    file(e) {
      if (e.target.files.length > 0) {
        // 获取图片
        const picture = e.target.files[0]
        // new一个构造函数
        const pic = new FileReader()
        // 转base格式
        pic.readAsDataURL(picture)
        pic.onload = () => {
          console.log(pic.result)
          this.url = pic.result
        }
      } else {
        this.url = ''
      }
    },
    async uploading() {
      const { data: res } = await updateAvatarAPI(this.url)
      // console.log(res)
      if (res.code === 0) {
        this.$message.success(res.message)
        // 更新成功，更新vuex中的 user 数据
        this.$store.dispatch('user/getUser')
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style>
.one {
  margin-top: 20px;
}
.two {
  width: 350px;
  height: 350px;
  border-radius: 50%;
  /* background-color: pink; */
  overflow:hidden
}
.two .img{
  object-fit: cover;
}
</style>
